var timeFlag; // 定时器的开关
var goods = {
    URL: {
        doSeckill:function () {
            return "/api/seckill";
        },
        now:function () {
            return "/api/time/now";
        },
        seckillPath:function (goodid) {
            return "/api/seckill/"+goodid+"/path";
        },
        queryResutl:function () {
            return "/api/seckill/result";
        },
        order:function () {
            return "/api/seckill/order";
        }
    },

    // 验证手机号
    validatePhone: function (phone) {
        if (phone && phone.length === 11 && !isNaN(phone)) {
            return true;
        } else {
            return false;
        }
    },
    countDown:function (goodId,nowTime,startTime,endTime) {
        var seckillCountDown = $("#seckill-count-down");
        if (nowTime>=endTime) {
            seckillCountDown.text("活动结束");
        } else if (nowTime<startTime) {
            var killTime = new Date(startTime);
            seckillCountDown.countdown(killTime, function (event) {
                var format = event.strftime("秒杀倒计时: %D天 %H时 %M分 %S秒");
                seckillCountDown.html(format);
            }).on('finish.countdown', function () {
                console.log("秒杀开始了");
                // 获取秒杀地址并开启秒杀
                goods.beginSeckill(goodId, nowTime, startTime, endTime, seckillCountDown);
            });
        } else {
                goods.beginSeckill(goodId, nowTime, startTime, endTime, seckillCountDown);
        }
    },
    beginSeckill:function (goodId, nowTime, startTime, endTime, node) {
        node.html('<button type="button" id="kill-btn" class="btn btn-danger">抢购</button>');

        // 获取秒杀地址
        $.get(goods.URL.seckillPath(goodId), function (res) {

            var md5 = res.data;
            console.log(md5);
            $("#kill-btn").one('click', function () {
                // 1.先禁用按钮
                $(this).addClass("disabled");
                //2.请求秒杀
                $.post(goods.URL.doSeckill(), {phone:$.cookie('killPhone'),randomName:md5}, function (res) {
                    if (0 === res.code) {
                        node.html('<span class="label label-success">' + "排队中，请稍等..." + '</span>');
                        // 每3秒轮询占位结果，取token来下单
                    } else {
                        node.html('<span class="label label-success">' + res.msg + '</span>');
                        $(this).removeClass("disabled");
                    }
                    timeFlag = window.setInterval(goods.queryResult, 3000, $.cookie('killPhone'), md5,goodId, node);

                });
            });
        });

    },
    queryResult:function (phone, randomName, goodId, node) {
        $.post(goods.URL.queryResutl(),{phone:phone, randomName:randomName},function (res) {
            if (0 === res.code && res.data) {
                // 停止定时任务
                clearInterval(timeFlag);
                // 把token 存下来
                $.cookie('token', res.data, {expires:1, path: ''});
                 node.html('您已获取到秒杀资格, 有效期3分钟，请立即下单：'+'<button class="btn btn-primary btn-lg" id="orderBtn">立即下单</button>');
                 $("#orderBtn").one('click', function () {
                     $(this).addClass("disabled");

                     // 发起秒杀请求
                     $.post(goods.URL.order(), {token:$.cookie("token"),goodId:goodId,phone:phone}, function (res) {
                        alert(res.msg);
                     }, 'json');
                 });
            }
        },'json');
    },
    //详情页秒杀逻辑
    detail:{
        init: function (params) {
            var killPhone = $.cookie('killPhone');

            // 验证手机号，失败了就弹框填写手机号
            if (!goods.validatePhone(killPhone)) {
                var killPhoneModal = $("#killPhoneModal");
                killPhoneModal.modal();
            }

            $("#killPhoneBtn").click(function () {
                var inputPhone = $("#killPhoneKey").val();
                if (goods.validatePhone(inputPhone)) {
                    $.cookie('killPhone', inputPhone, {expires:7, path:''});
                    window.location.reload();
                } else {
                    $("#errorMessage").hide().html('<label class="label label-danger">手机号错误!</label>').show(300);
                }
            });

            // 已登录的交互
            var startTime = params.startTime;
            var endTime = params.endTime;
            var goodsId = params.goodId;

            $('#userPhone').text(killPhone);
            
            $('#logout').click(function () {
                $.cookie('killPhone', null, {expires:0, path: ''});
                window.location.reload();
            });

            //获取当前服务器时间
            $.get(goods.URL.now(), function (res) {
                console.log(res);
                if (0 === res.code) {
                    var nowTime = res.data;
                    goods.countDown(goodsId, nowTime, startTime, endTime);
                } else {
                    alert(res.msg);
                }
            }, 'json');
        }
    }
};